package com.hy.mydesktop.client.mvc.panel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.data.BaseListLoadResult;
import com.extjs.gxt.ui.client.data.BaseListLoader;
import com.extjs.gxt.ui.client.data.BaseModel;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.hy.mydesktop.client.MyDesktop;
import com.hy.mydesktop.client.component.event.AppEvents;
import com.hy.mydesktop.client.component.factory.GxtComponentFactory;
import com.hy.mydesktop.client.component.mvc.event.EventStructureMetaModel;
import com.hy.mydesktop.client.mvc.base.BaseController;
import com.hy.mydesktop.client.mvc.util.ControllerUtil;
import com.hy.mydesktop.client.mvc.window.WindowDisplay;
import com.hy.mydesktop.client.rpc.ServiceInvoker;
import com.hy.mydesktop.client.rpc.ServiceInvokerAsync;
import com.hy.mydesktop.shared.rpc.meta.GxtToSeamServiceParameter;
import com.hy.mydesktop.shared.rpc.meta.GxtToSeamServiceResult;

public class FormPanelControler extends BaseController  {
	
	private FormPanelPresenter FormPanelPresenter;
	
	public FormPanelControler() {
		super();
		super.printControllerForInit(getClass());

	  }

	@Override
	public void handleEvent(AppEvent event) {
		final Map<String, Object> map = (Map<String, Object>)event.getData();
		EventStructureMetaModel eventStructureMetaModel =null;
		if (map!=null) {
			eventStructureMetaModel =(EventStructureMetaModel)map.get("eventstructuremetamodel");
		}
		//EventStructureMetaModel eventStructureMetaModel =(EventStructureMetaModel)((Map<String, Object>)event.getData()).get("eventstructuremetamodel");
		//0007
		if (AppEvents.DESKTOP_WINDOWAPPLICATION_INIT==event.getType()) {
			//if (eventStructureMetaModel==null||this.getId()==null||eventStructureMetaModel.getControllerId()==null||eventStructureMetaModel.getControllerId().equals(this.getId())) {
			if (ControllerUtil.isHandle(eventStructureMetaModel, this)) {
	
			//转发到视图View
				forwardToView(FormPanelPresenter, event);
				
				/**
				 * 获取Controller对应的View的组件Component
				 * 把Component，作为事件的一部分，向下传递
				 * map.put("parent", windowView.getWindow());
				 * 此方法错误
				 */
				Map<BaseController, Component> subMap = (Map<BaseController, Component>)map.get("controllerandcomponent");;
						subMap.put(this,  FormPanelPresenter.getDisplay().getComponent());
				/**
				 * 把Controller和,与之对应的Component放入Map（为了方便查找Component的父元素）
				 */
				map.put("controllerandcomponent", subMap);
				/**
				 * 如何知道事件已经转发完毕
				 * 
				 * 方法1 ： 计数器		
				 */
				
				if (this.getChildren()!=null&&this.getChildren().size()>0) {
					/**
					 * 将事件转发给子节点，及子控制器
					 * 注:当前控制器，含有子节点的时候，必不可少
					 * 
					 * 采用先序遍历的方式---树
					 */
					this.forwardToChild(new AppEvent(AppEvents.DESKTOP_WINDOWAPPLICATION_INIT,map));
				} /*else {
					
					*//**
					 * 如果当前控制器，有子节点，则向下转发事件，
					 * 否则渲染组件，即渲染顶级元素
					 * 如何渲染顶级元素，即Window ？
					 *//*
					forwardToView(windowView,  AppEvents.DESKTOP_APPLICATION_RENDER,event.getData());
				}*/
				/*int count =( (Integer)map.get("count")-1);
				if (count<=0) {
					Dispatcher.forwardEvent(AppEvents.DESKTOP_APPLICATION_RENDER,map);
				}else {
					map.put("count", count);
				}*/
				ControllerUtil.isRenderer(map);

			}else {
				this.forwardToChild(event);

			}
		}
		
		//0304
		else if (AppEvents.FORM_DATALOAD==event.getType()) {
			//if (eventStructureMetaModel==null||this.getId()==null||eventStructureMetaModel.getControllerId()==null||eventStructureMetaModel.getControllerId().equals(this.getId())) {
			if (ControllerUtil.isHandle(eventStructureMetaModel, this)) {
			
			
					String dataObjectId = (String)map.get("dataObjectId");									
					final GxtToSeamServiceParameter gxtToSeamServiceParameter = FormPanelPresenter.getDisplay().getComponent().getData("gxtToSeamServiceParameterForQuery");
					
					
					/*gxtToSeamServiceParameter.setServiceComponentName("com.hy.mydesktop.server.business.PersonService");
					gxtToSeamServiceParameter.setServiceMethodName("listPerson2");*/
					BaseModel[] methodArguments = new BaseModel[1];
					methodArguments[0] = new BaseModel();
					methodArguments[0].set("identifier", dataObjectId);
					gxtToSeamServiceParameter.setMethodArguments(methodArguments );	
//					final ServiceInvokerAsync serviceInvoker = GWT.create(ServiceInvoker.class);
					final ServiceInvokerAsync serviceInvoker = Registry.get(MyDesktop.SERVICEINVOKER);
					 RpcProxy<GxtToSeamServiceResult> proxy = null;

					if (gxtToSeamServiceParameter!=null) {
						
						
						serviceInvoker.callService(gxtToSeamServiceParameter,
								new AsyncCallback<GxtToSeamServiceResult>() {

									@Override
									public void onSuccess(GxtToSeamServiceResult result) {
										List<BaseModel> bmBaseModels = new LinkedList<BaseModel>();
										ModelData modelData = result.getResult();
										bmBaseModels = modelData.get("listOfModelData");
																	
										
										BaseModel baseModel = bmBaseModels.get(0);										
										map.put("formData", baseModel);
										
										FormPanelPresenter.getDisplay().getComponent().setData("formDataForSubmit",baseModel);

										//2222222222222222
										Dispatcher.forwardEvent(AppEvents.FORM_FIELD_DATALOAD, map);
									}

									@Override
									public void onFailure(Throwable caught) {
										System.out.println("------Rpc Exception is ####"+caught +"When formPanel get his data");
										caught.printStackTrace();
									}
								});
					
					}													
					//转发到视图View
				/*forwardToView(FormPanelPresenter, event);
			
				if (this.getChildren()!=null&&this.getChildren().size()>0) {
					*//**
					 * 将事件转发给子节点，及子控制器
					 * 注:当前控制器，含有子节点的时候，必不可少
					 * 采用先序遍历的方式---树
					 *//*
					this.forwardToChild(new AppEvent(AppEvents.FORM_FIELD_DATALOAD,map));
				}*/				
				ControllerUtil.isRenderer(map);

			}else {
				this.forwardToChild(event);

			}		
		}
		
		//0000
		//如果当前控制器，不能处理该事件，则向下转发
		else {
			this.forwardToChild(event);
		}
	}
	
	public void initialize() {
		FormPanel  formPanel = GxtComponentFactory.createOneGxtComponent(getGxtComponentMetaNodeModel());			
		FormPanelDisplay formPanelDisplay = new FormPanelDisplay(formPanel);
		FormPanelPresenter = new FormPanelPresenter(this,formPanelDisplay);

	  }
	
	protected void onError(AppEvent ae) {
	    System.out.println("error: " + ae.<Object>getData());
	  }
}
